<template>
  <div class="orders-page">
    <!-- 页面标题 -->
    <t-card class="header-card">
      <div class="card-header">
        <h2 class="page-title">订单管理</h2>
        <t-space>
          <t-button theme="default" @click="exportOrdersData">
            <template #icon><t-icon name="download" /></template>
            导出数据
          </t-button>
        </t-space>
      </div>
    </t-card>
    
    <!-- 搜索和筛选 -->
    <t-card class="filter-card">
      <t-form layout="inline" :data="searchForm" @reset="handleSearchReset" @submit="handleSearchSubmit">
        <t-form-item label="关键字" name="keyword">
          <t-input
            v-model="searchForm.keyword"
            placeholder="订单号/姓名/手机号"
            clearable
          />
        </t-form-item>
        <t-form-item label="订单类型" name="orderType">
          <t-select
            v-model="searchForm.orderType"
            placeholder="请选择订单类型"
            clearable
            style="width: 150px"
          >
            <t-option
              v-for="(label, value) in orderTypeOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="订单状态" name="orderStatus">
          <t-select
            v-model="searchForm.orderStatus"
            placeholder="请选择订单状态"
            clearable
            style="width: 150px"
          >
            <t-option
              v-for="(label, value) in orderStatusOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </t-select>
        </t-form-item>
        <t-form-item label="下单时间" name="dateRange">
          <t-date-range-picker
            v-model="dateRange"
            clearable
            style="width: 300px"
            @change="handleDateRangeChange"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="primary" type="submit">
              <template #icon><t-icon name="search" /></template>
              搜索
            </t-button>
            <t-button theme="default" type="reset">重置</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-card>
    
    <!-- 订单列表表格 -->
    <t-card class="table-card">
      <t-table
        :data="orderList"
        :columns="columns"
        :row-key="rowKey"
        :loading="tableLoading"
        :pagination="pagination"
        :hover="true"
        @page-change="onPageChange"
      >
        <!-- 订单号列 -->
        <template #orderNo="{ row }">
          <div class="order-no">
            <t-link theme="primary" hover="color" @click="handleViewDetail(row)">{{ row.orderNo }}</t-link>
          </div>
        </template>
        
        <!-- 产品信息列 -->
        <template #product="{ row }">
          <div class="product-info">
            <div class="product-name">{{ row.productName }}</div>
            <div class="product-meta">
              {{ getOrderTypeLabel(row.orderType) }} | {{ row.productQuantity }}份
            </div>
          </div>
        </template>
        
        <!-- 用户信息列 -->
        <template #user="{ row }">
          <div class="user-info">
            <div>{{ row.userName }}</div>
            <div class="user-phone">{{ row.userPhone }}</div>
          </div>
        </template>
        
        <!-- 金额列 -->
        <template #amount="{ row }">
          <div class="amount-info">
            <div class="amount-value">¥{{ formatCurrency(row.paymentAmount) }}</div>
            <div class="payment-method" v-if="row.paymentMethod">
              {{ getPaymentMethodLabel(row.paymentMethod) }}
            </div>
          </div>
        </template>
        
        <!-- 订单状态列 -->
        <template #status="{ row }">
          <t-tag :theme="getStatusTheme(row.orderStatus)">
            {{ getOrderStatusLabel(row.orderStatus) }}
          </t-tag>
        </template>
        
        <!-- 下单时间列 -->
        <template #createTime="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
        
        <!-- 操作列 -->
        <template #operation="{ row }">
          <t-space>
            <t-link theme="primary" hover="color" @click="handleViewDetail(row)">查看</t-link>
            <t-dropdown :options="getActionOptions(row)" @click="handleAction(row, $event)">
              <t-link theme="primary" hover="color">更多</t-link>
            </t-dropdown>
          </t-space>
        </template>
      </t-table>
    </t-card>
    
    <!-- 订单详情对话框 -->
    <t-dialog
      v-model:visible="detailVisible"
      header="订单详情"
      width="800px"
      :footer="false"
    >
      <order-detail 
        v-if="detailData" 
        :order-data="detailData"
        @status-change="handleStatusChange"
        @remark-change="handleRemarkChange"
      />
    </t-dialog>
    
    <!-- 订单取消对话框 -->
    <t-dialog
      v-model:visible="cancelVisible"
      header="取消订单"
      width="500px"
      :footer="false"
    >
      <t-form :data="cancelForm" @submit="handleCancelSubmit">
        <t-form-item label="取消原因" name="reason">
          <t-textarea
            v-model="cancelForm.reason"
            placeholder="请输入取消原因"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="cancelVisible = false">取消</t-button>
            <t-button theme="danger" type="submit" :loading="submitLoading">确认取消订单</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 退款申请对话框 -->
    <t-dialog
      v-model:visible="refundVisible"
      header="申请退款"
      width="500px"
      :footer="false"
    >
      <t-form :data="refundForm" @submit="handleRefundSubmit">
        <t-form-item label="订单金额">
          <div>¥{{ formatCurrency(currentOrder?.paymentAmount || 0) }}</div>
        </t-form-item>
        <t-form-item label="退款金额" name="amount">
          <t-input-number
            v-model="refundForm.amount"
            :min="0"
            :max="currentOrder?.paymentAmount || 0"
            step="0.01"
            theme="normal"
          />
        </t-form-item>
        <t-form-item label="退款原因" name="reason">
          <t-textarea
            v-model="refundForm.reason"
            placeholder="请输入退款原因"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="refundVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitLoading">确认退款</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
    
    <!-- 订单备注对话框 -->
    <t-dialog
      v-model:visible="remarkVisible"
      header="编辑备注"
      width="500px"
      :footer="false"
    >
      <t-form :data="remarkForm" @submit="handleRemarkSubmit">
        <t-form-item label="订单备注" name="remark">
          <t-textarea
            v-model="remarkForm.remark"
            placeholder="请输入订单备注"
            :autosize="{ minRows: 3, maxRows: 8 }"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="default" @click="remarkVisible = false">取消</t-button>
            <t-button theme="primary" type="submit" :loading="submitLoading">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { PrimaryTableCol, TableRowData, PageInfo, DropdownOption } from 'tdesign-vue-next'
import {
  getOrders,
  getOrderDetail,
  updateOrderStatus,
  confirmOrder,
  completeOrder,
  cancelOrder,
  requestRefund,
  confirmRefund,
  updateOrderRemark,
  exportOrders,
  type Order,
  OrderStatus,
  OrderType,
  PaymentMethod
} from '../../api/orders'

// 导入订单详情组件
import OrderDetail from './components/OrderDetail.vue'

// 订单类型选项
const orderTypeOptions: Record<string, string> = {
  [OrderType.TICKET]: '门票订单',
  [OrderType.HOTEL]: '酒店订单',
  [OrderType.ACTIVITY]: '活动订单',
  [OrderType.PACKAGE]: '套餐订单'
}

// 订单状态选项
const orderStatusOptions: Record<string, string> = {
  [OrderStatus.PENDING]: '待支付',
  [OrderStatus.PAID]: '已支付',
  [OrderStatus.CONFIRMED]: '已确认',
  [OrderStatus.COMPLETED]: '已完成',
  [OrderStatus.CANCELLED]: '已取消',
  [OrderStatus.REFUNDING]: '退款中',
  [OrderStatus.REFUNDED]: '已退款'
}

// 支付方式选项
const paymentMethodOptions: Record<string, string> = {
  [PaymentMethod.WECHAT]: '微信支付',
  [PaymentMethod.ALIPAY]: '支付宝',
  [PaymentMethod.BANK]: '银行卡',
  [PaymentMethod.CASH]: '现金',
  [PaymentMethod.OTHER]: '其他方式'
}

// 表格列定义
const columns: PrimaryTableCol[] = [
  {
    colKey: 'orderNo',
    title: '订单号',
    width: 160,
    cell: 'orderNo'
  },
  {
    colKey: 'product',
    title: '产品信息',
    width: 200,
    cell: 'product'
  },
  {
    colKey: 'user',
    title: '用户信息',
    width: 160,
    cell: 'user'
  },
  {
    colKey: 'amount',
    title: '订单金额',
    width: 150,
    cell: 'amount'
  },
  {
    colKey: 'status',
    title: '订单状态',
    width: 120,
    cell: 'status'
  },
  {
    colKey: 'createTime',
    title: '下单时间',
    width: 160,
    cell: 'createTime'
  },
  {
    colKey: 'operation',
    title: '操作',
    fixed: 'right',
    width: 150,
    cell: 'operation'
  }
]

// 表格数据
const orderList = ref<Order[]>([])
const tableLoading = ref(false)
const rowKey = 'id'

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  orderType: '',
  orderStatus: '',
  startDate: '',
  endDate: ''
})

// 日期范围选择
const dateRange = ref<[string, string]>(['', ''])

// 详情对话框
const detailVisible = ref(false)
const detailData = ref<Order | null>(null)

// 当前操作的订单
const currentOrder = ref<Order | null>(null)

// 取消订单
const cancelVisible = ref(false)
const cancelForm = reactive({
  reason: ''
})

// 申请退款
const refundVisible = ref(false)
const refundForm = reactive({
  amount: 0,
  reason: ''
})

// 编辑备注
const remarkVisible = ref(false)
const remarkForm = reactive({
  remark: ''
})

// 提交状态
const submitLoading = ref(false)

// 初始化
onMounted(() => {
  fetchOrderList()
})

// 获取订单列表
const fetchOrderList = async () => {
  tableLoading.value = true
  try {
    const result = await getOrders({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword || undefined,
      orderType: searchForm.orderType as OrderType || undefined,
      orderStatus: searchForm.orderStatus as OrderStatus || undefined,
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined
    })
    
    orderList.value = result.list || []
    pagination.total = result.total || 0
  } catch (error) {
    console.error('获取订单列表失败', error)
    MessagePlugin.error('获取订单列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化货币
const formatCurrency = (value: number) => {
  return value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取订单类型标签
const getOrderTypeLabel = (type: OrderType) => {
  return orderTypeOptions[type] || type
}

// 获取订单状态标签
const getOrderStatusLabel = (status: OrderStatus) => {
  return orderStatusOptions[status] || status
}

// 获取支付方式标签
const getPaymentMethodLabel = (method: PaymentMethod) => {
  return paymentMethodOptions[method] || method
}

// 获取状态对应的主题色
const getStatusTheme = (status: OrderStatus) => {
  const themeMap: Record<OrderStatus, 'default' | 'primary' | 'warning' | 'success' | 'danger'> = {
    [OrderStatus.PENDING]: 'warning',
    [OrderStatus.PAID]: 'primary',
    [OrderStatus.CONFIRMED]: 'primary',
    [OrderStatus.COMPLETED]: 'success',
    [OrderStatus.CANCELLED]: 'default',
    [OrderStatus.REFUNDING]: 'warning',
    [OrderStatus.REFUNDED]: 'default'
  }
  return themeMap[status] || 'default'
}

// 获取可用的操作选项
const getActionOptions = (order: Order): DropdownOption[] => {
  const options: DropdownOption[] = [
    { content: '编辑备注', value: 'editRemark' }
  ]
  
  switch (order.orderStatus) {
    case OrderStatus.PAID:
      options.unshift({ content: '确认订单', value: 'confirm' })
      options.push({ content: '申请退款', value: 'refund' })
      options.push({ content: '取消订单', value: 'cancel' })
      break
    case OrderStatus.CONFIRMED:
      options.unshift({ content: '完成订单', value: 'complete' })
      options.push({ content: '申请退款', value: 'refund' })
      break
    case OrderStatus.PENDING:
      options.push({ content: '取消订单', value: 'cancel' })
      break
  }
  
  return options
}

// 处理日期范围变化
const handleDateRangeChange = (value: [string, string]) => {
  if (value && value.length === 2) {
    searchForm.startDate = value[0]
    searchForm.endDate = value[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

// 分页变化
const onPageChange = (pageInfo: PageInfo) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  fetchOrderList()
}

// 搜索表单提交
const handleSearchSubmit = () => {
  pagination.current = 1
  fetchOrderList()
}

// 搜索表单重置
const handleSearchReset = () => {
  dateRange.value = ['', '']
  pagination.current = 1
  fetchOrderList()
}

// 查看订单详情
const handleViewDetail = async (row: Order) => {
  try {
    const data = await getOrderDetail(row.id)
    detailData.value = data
    detailVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败', error)
    MessagePlugin.error('获取订单详情失败')
  }
}

// 处理更多操作
const handleAction = (order: Order, option: { value: string }) => {
  currentOrder.value = order
  
  switch (option.value) {
    case 'confirm':
      handleConfirmOrder(order)
      break
    case 'complete':
      handleCompleteOrder(order)
      break
    case 'cancel':
      showCancelDialog(order)
      break
    case 'refund':
      showRefundDialog(order)
      break
    case 'editRemark':
      showRemarkDialog(order)
      break
  }
}

// 确认订单
const handleConfirmOrder = async (order: Order) => {
  try {
    await confirmOrder(order.id)
    MessagePlugin.success('订单已确认')
    fetchOrderList()
    
    // 如果详情页打开，刷新详情
    if (detailVisible.value && detailData.value && detailData.value.id === order.id) {
      const data = await getOrderDetail(order.id)
      detailData.value = data
    }
  } catch (error) {
    console.error('确认订单失败', error)
    MessagePlugin.error('确认订单失败')
  }
}

// 完成订单
const handleCompleteOrder = async (order: Order) => {
  try {
    await completeOrder(order.id)
    MessagePlugin.success('订单已完成')
    fetchOrderList()
    
    // 如果详情页打开，刷新详情
    if (detailVisible.value && detailData.value && detailData.value.id === order.id) {
      const data = await getOrderDetail(order.id)
      detailData.value = data
    }
  } catch (error) {
    console.error('完成订单失败', error)
    MessagePlugin.error('完成订单失败')
  }
}

// 显示取消订单对话框
const showCancelDialog = (order: Order) => {
  cancelForm.reason = ''
  cancelVisible.value = true
}

// 提交取消订单
const handleCancelSubmit = async () => {
  if (!currentOrder.value) return
  if (!cancelForm.reason.trim()) {
    MessagePlugin.warning('请输入取消原因')
    return
  }
  
  submitLoading.value = true
  try {
    await cancelOrder(currentOrder.value.id, cancelForm.reason)
    MessagePlugin.success('订单已取消')
    cancelVisible.value = false
    fetchOrderList()
    
    // 如果详情页打开，刷新详情
    if (detailVisible.value && detailData.value && detailData.value.id === currentOrder.value.id) {
      const data = await getOrderDetail(currentOrder.value.id)
      detailData.value = data
    }
  } catch (error) {
    console.error('取消订单失败', error)
    MessagePlugin.error('取消订单失败')
  } finally {
    submitLoading.value = false
  }
}

// 显示退款对话框
const showRefundDialog = (order: Order) => {
  refundForm.amount = order.paymentAmount
  refundForm.reason = ''
  refundVisible.value = true
}

// 提交退款申请
const handleRefundSubmit = async () => {
  if (!currentOrder.value) return
  if (refundForm.amount <= 0) {
    MessagePlugin.warning('退款金额必须大于0')
    return
  }
  if (!refundForm.reason.trim()) {
    MessagePlugin.warning('请输入退款原因')
    return
  }
  
  submitLoading.value = true
  try {
    await requestRefund(currentOrder.value.id, refundForm.reason, refundForm.amount)
    MessagePlugin.success('退款申请已提交')
    refundVisible.value = false
    fetchOrderList()
    
    // 如果详情页打开，刷新详情
    if (detailVisible.value && detailData.value && detailData.value.id === currentOrder.value.id) {
      const data = await getOrderDetail(currentOrder.value.id)
      detailData.value = data
    }
  } catch (error) {
    console.error('申请退款失败', error)
    MessagePlugin.error('申请退款失败')
  } finally {
    submitLoading.value = false
  }
}

// 显示备注对话框
const showRemarkDialog = (order: Order) => {
  remarkForm.remark = order.remark || ''
  remarkVisible.value = true
}

// 提交备注
const handleRemarkSubmit = async () => {
  if (!currentOrder.value) return
  
  submitLoading.value = true
  try {
    await updateOrderRemark(currentOrder.value.id, remarkForm.remark)
    MessagePlugin.success('备注已更新')
    remarkVisible.value = false
    fetchOrderList()
    
    // 如果详情页打开，刷新详情
    if (detailVisible.value && detailData.value && detailData.value.id === currentOrder.value.id) {
      const data = await getOrderDetail(currentOrder.value.id)
      detailData.value = data
    }
  } catch (error) {
    console.error('更新备注失败', error)
    MessagePlugin.error('更新备注失败')
  } finally {
    submitLoading.value = false
  }
}

// 处理订单状态变更（从详情组件触发）
const handleStatusChange = async () => {
  fetchOrderList()
}

// 处理备注变更（从详情组件触发）
const handleRemarkChange = async () => {
  fetchOrderList()
}

// 导出订单数据
const exportOrdersData = async () => {
  try {
    const blob = await exportOrders({
      keyword: searchForm.keyword || undefined,
      orderType: searchForm.orderType as OrderType || undefined,
      orderStatus: searchForm.orderStatus as OrderStatus || undefined,
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `orders_${new Date().getTime()}.xlsx`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    
    MessagePlugin.success('订单数据导出成功')
  } catch (error) {
    console.error('导出订单失败', error)
    MessagePlugin.error('导出订单失败')
  }
}
</script>

<style scoped>
.orders-page {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.order-no {
  font-family: monospace;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-meta {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-phone {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
}

.amount-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.amount-value {
  font-weight: 500;
}

.payment-method {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
}
</style>
